package com.example.provider.javastudy.invokedynamic;

import java.lang.invoke.*;

import static java.lang.invoke.MethodHandles.lookup;

/**
 * All rights Reserved, Designed By www.maihaoche.com
 *
 * @Package com.example.demo.invokedynamic
 * @author: 红雪（hongxue@maihaoche.com）
 * @date: 2019/1/15 11:20 AM
 * @Copyright: 2017-2020 www.maihaoche.com Inc. All rights reserved.
 * 注意：本内容仅限于卖好车内部传阅，禁止外泄以及用于其他的商业项目
 */
public class InvokeDymamicTest {

    public static void main(String[] args) throws Throwable {
        INDY_BootstrapMethod().invokeExact("durui");
    }

    public static void  testMethod(String s){
        System.out.println("hello String"+s);
    }

    public static CallSite BootstrapMethod(MethodHandles.Lookup lookup, String name, MethodType mt) throws NoSuchMethodException, IllegalAccessException {
        return new ConstantCallSite(lookup.findStatic(InvokeDymamicTest.class,name,mt));

    }

    /*调用的实际上是BootstrapMthod方法*/
    private static MethodType MT_BootstrapMethod(){
        return MethodType.fromMethodDescriptorString("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",null);
    }

    /*调用的实际上是BootstrapMthod方法*/
    private static MethodHandle MH_BootstrapMethod() throws NoSuchMethodException, IllegalAccessException {
        return lookup().findStatic(InvokeDymamicTest.class,"BootstrapMethod",MT_BootstrapMethod());
    }

    private static MethodHandle INDY_BootstrapMethod() throws Throwable {
        CallSite cs = (CallSite) MH_BootstrapMethod().invokeWithArguments(lookup(),"testMethod",MethodType.fromMethodDescriptorString("(Ljava/lang/String;)V",null));
        return cs.dynamicInvoker();
    }
}
